import { getBaseInfo } from '@src/api/member'
import { getQrcode } from '@src/api/loan'
import member from '@src/store/member'
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: member,
      fields: ['wxHeadImg'],
    },
  ],
  data: {
    postImg: '',
    userInfo: {},
    CanvasWidth: 200,
    CanvasHeight: 200,
    qrBg: '',
    qrWhiteBg: '',
    avater: '',
    canRatio: '',
    canvasUrl: '',
    qrCodeParams: {
      appId: '',
      page: 'pages/loanMove/pages/index/main',
      scene: '',
      openId: '',
    },
    qrCode: '',
  },
  methods: {
    onLogin() {
      this.setOpenid()
    },
    onLoad(options) {},
    onReady() {
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline'],
      })
    },
    onShareAppMessage(e) {
      return {
        title: '给你分享一个好东西',
        imageUrl: '',
        path: `pages/loanMove/pages/index/main?openId=${this.data.userInfo.openId}&tweeterPhone=${this.data.userInfo.phone}`,
        success: (res) => {},
      }
    },
    // 获取当前用户信息
    setOpenid() {
      let { appId } = getApp().globalData.extConfig
      getBaseInfo().then((res) => {
        if (res.data.openId) {
          this.setData({
            userInfo: res.data,
            codeStatus: res.code,
            'qrCodeParams.appId': appId,
            'qrCodeParams.scene': res.data.openId,
            'qrCodeParams.openId': res.data.openId,
            'qrCodeParams.tweeterPhone': res.data.phone,
          })
          getQrcode(this.data.qrCodeParams).then((res) => {
            if (res.code == 0) {
              wx.getImageInfo({
                src: res.data.data,
                success: (res) => {
                  this.setData({ qrCode: res.path })
                  this.initCanvasOption()
                },
              })
            }
          })
        }
      })
    },
    //保存到相册
    handleSavePost() {
      let { canvasUrl } = this.data
      if (!canvasUrl) {
        wx.showToast({ title: '保存图片失败,请稍后重试' })
        this.drawPosters()
        return
      }
      wx.saveImageToPhotosAlbum({
        filePath: canvasUrl,
        success: () => {
          wx.showToast({
            title: `海报已保存到系统相册`,
            icon: 'none',
            duration: 3000,
          })
        },
        fail: (err) => {
          console.log(err)
          if (
            err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied' ||
            err.errMsg === 'saveImageToPhotosAlbum:fail auth deny'
          ) {
            // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
            wx.showModal({
              title: '提示',
              content: '需要您授权保存相册',
              showCancel: false,
              success: () => {
                wx.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      this.handleSavePost()
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '获取保存到相册权限失败，将无法保存到相册',
                        showCancel: false,
                      })
                    }
                  },
                })
              },
            })
          }
        },
      })
    },
    initCanvasOption() {
      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            CanvasWidth: res.windowWidth,
            CanvasHeight: res.windowHeight - this.data.navBarHeight,
          })
          wx.getImageInfo({
            src:
              'https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/img/uploads/signQr_bg.png',
            success: (res) => {
              this.setData({ qrBg: res.path })
              wx.getImageInfo({
                src:
                  'https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/img/uploads/qr_bg_1.png',
                success: (res) => {
                  this.setData({ qrWhiteBg: res.path })
                  wx.getImageInfo({
                    src: this.data.wxHeadImg,
                    success: (res) => {
                      this.setData({ avater: res.path })
                      this.drawPosters()
                    },
                  })
                },
              })
            },
          })
        },
      })
    },
    // 绘制背景图片
    drawBg(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio) {
      let { qrBg } = this.data
      context.save()
      context.beginPath()
      context.drawImage(qrBg, 0, 0, CanvasWidth, CanvasHeight)
      context.restore()
    },
    // 绘制白色背景图片
    drawWhiteBg(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio) {
      let { qrWhiteBg } = this.data
      let white_x = 40 * widthRatio
      let white_y = CanvasHeight * 0.37
      let white_width = CanvasWidth - 80 * widthRatio
      let white_height = 740 * heightRatio
      context.save()
      context.beginPath()
      context.drawImage(qrWhiteBg, white_x, white_y, white_width, white_height)
      context.restore()
    },
    // 绘制头像
    drawAvater(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio) {
      let { avater } = this.data
      let avatarurl_width = 70
      let avatarurl_heigth = 70
      let avatarurl_x = CanvasWidth / 2 - avatarurl_width / 2
      let avatarurl_y = 415 * heightRatio
      context.save()
      context.beginPath()
      context.arc(
        avatarurl_width / 2 + avatarurl_x,
        avatarurl_heigth / 2 + avatarurl_y,
        avatarurl_width / 2,
        0,
        Math.PI * 2,
        false,
      )
      context.clip()
      context.setFillStyle('#fff')
      context.drawImage(
        avater,
        avatarurl_x,
        avatarurl_y,
        avatarurl_width,
        avatarurl_heigth,
      )
      context.restore()
    },
    // 绘制二维码
    drawQrcode(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio) {
      let { qrCode } = this.data
      let qr_width = 200
      let qr_height = 200
      let qr_x = CanvasWidth / 2 - qr_width / 2
      let qr_y = 611 * heightRatio
      context.save()
      context.beginPath()
      context.arc(
        qr_width / 2 + qr_x,
        qr_height / 2 + qr_y,
        qr_width / 2,
        0,
        Math.PI * 2,
        false,
      )
      context.clip()
      context.setFillStyle('#fff')
      context.drawImage(qrCode, qr_x, qr_y, qr_width, qr_height)
      context.restore()
    },
    // 绘制文本
    drawText(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio) {
      let text1 = '您的好友邀请您参与报名'
      let text2 = '长按识别二维码'
      let fontSize = 14
      let qr_y = 611 * heightRatio
      context.setFontSize(fontSize)
      context.setFillStyle('#131313')
      context.setGlobalAlpha('0.6')
      context.fillText(
        text1,
        CanvasWidth / 2 - (text1.length / 2) * fontSize,
        qr_y + 240,
      )
      context.fillText(
        text2,
        CanvasWidth / 2 - (text2.length / 2) * fontSize,
        qr_y + 260,
      )
    },
    drawPosters() {
      let { CanvasWidth, CanvasHeight } = this.data
      let widthRatio = CanvasWidth / 750
      let heightRatio = CanvasHeight / 1280
      var context = wx.createCanvasContext('canvasID')
      context.setLineWidth(0)
      // 绘制背景图片
      this.drawBg(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio)
      this.drawWhiteBg(
        context,
        CanvasWidth,
        CanvasHeight,
        widthRatio,
        heightRatio,
      )
      this.drawAvater(
        context,
        CanvasWidth,
        CanvasHeight,
        widthRatio,
        heightRatio,
      )
      this.drawQrcode(
        context,
        CanvasWidth,
        CanvasHeight,
        widthRatio,
        heightRatio,
      )
      this.drawText(context, CanvasWidth, CanvasHeight, widthRatio, heightRatio)
      context.draw()
      context.save()
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'canvasID',
          success: (res) => {
            if (res.errMsg == 'canvasToTempFilePath:ok') {
              this.setData({ canvasUrl: res.tempFilePath })
            }
          },
          fail: function () {
            console.log('生成海报失败')
          },
          complete() {
            wx.hideLoading()
            wx.hideToast()
          },
        })
      }, 500)
    },
  },
})
